<template>
  <div class="smart-image-container" :style="containerStyle">
    <img
      :src="src"
      :height="height"
      :width="width"
      :alt="alt"
      :class="imageClass"
      :style="imageStyle"
      @load="onImageLoad"
      @error="onImageError"
      ref="imgRef"
      crossorigin="anonymous"
    />
    <!-- 用于颜色分析的隐藏canvas -->
    <canvas ref="canvasRef" style="display: none;"></canvas>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, nextTick } from 'vue'

interface ColorInfo {
  r: number
  g: number
  b: number
  brightness: number
  isLight: boolean
}

interface ImageAnalysis {
  dominantColor: ColorInfo
  averageColor: ColorInfo
  hasTransparency: boolean
  needsBackground: boolean
  recommendedBackground: string
}

const props = defineProps<{
  src: string
  height?: number | string
  width?: number | string
  alt?: string
  autoBackground?: boolean // 是否启用自动背景识别
  backgroundType?: 'auto' | 'solid' | 'gradient' | 'shadow' | 'border' | 'contrast' // 背景类型
  backgroundColor?: string // 自定义背景色
  borderRadius?: string // 圆角
  contrastThreshold?: number // 对比度阈值 (0-1)
}>()

const emit = defineEmits<{
  load: [event: Event]
  error: [event: Event]
  analyzed: [analysis: ImageAnalysis]
}>()

const imgRef = ref<HTMLImageElement>()
const canvasRef = ref<HTMLCanvasElement>()
const isLoaded = ref(false)
const hasError = ref(false)
const imageAnalysis = ref<ImageAnalysis | null>(null)

const containerStyle = computed(() => {
  const style: Record<string, string> = {}
  
  if (props.borderRadius) {
    style.borderRadius = props.borderRadius
  }
  
  if (props.backgroundType === 'shadow') {
    style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.2)'
  }
  
  return style
})

const imageStyle = computed(() => {
  if (!isLoaded.value) return {}
  
  const style: Record<string, string> = {}
  
  // 如果有分析结果且启用自动背景
  if (imageAnalysis.value && (props.autoBackground || props.backgroundType === 'auto')) {
    if (imageAnalysis.value.needsBackground) {
      style.backgroundColor = imageAnalysis.value.recommendedBackground
      style.padding = '4px'
    }
  } else {
    // 手动设置的背景类型
    switch (props.backgroundType) {
      case 'solid':
        style.backgroundColor = props.backgroundColor || 'rgba(255, 255, 255, 0.4)'
        style.padding = '4px'
        break
      case 'gradient':
        style.background = 'linear-gradient(135deg, rgba(255,255,255,0.9) 0%, rgba(240,240,240,0.9) 100%)'
        style.padding = '4px'
        break
      case 'border':
        style.border = '2px solid rgba(255, 255, 255, 0.5)'
        break
      case 'contrast':
        if (imageAnalysis.value) {
          const { dominantColor } = imageAnalysis.value
          const contrastColor = dominantColor.isLight 
            ? 'rgba(0, 0, 0, 0.3)' 
            : 'rgba(255, 255, 255, 0.9)'
          style.backgroundColor = contrastColor
          style.padding = '4px'
        }
        break
      case 'shadow':
        // 阴影在容器上设置
        break
      default:
        if (props.backgroundColor) {
          style.backgroundColor = props.backgroundColor
          style.padding = '2px'
        }
    }
  }
  
  if (props.borderRadius) {
    style.borderRadius = props.borderRadius
  }
  
  return style
})

const imageClass = computed(() => {
  const classes = ['smart-image']
  if (hasError.value) classes.push('error')
  if (isLoaded.value) classes.push('loaded')
  return classes.join(' ')
})

function onImageLoad(event: Event) {
  isLoaded.value = true
  hasError.value = false
  emit('load', event)
  
  if (props.autoBackground || props.backgroundType === 'auto' || props.backgroundType === 'contrast') {
    nextTick(() => {
      analyzeImage()
    })
  }
}

function onImageError(event: Event) {
  hasError.value = true
  isLoaded.value = false
  emit('error', event)
}

// 分析图片颜色和透明度
function analyzeImage() {
  if (!imgRef.value) return
  
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  const img = imgRef.value
  
  // 设置canvas尺寸（使用较小尺寸以提高性能）
  const maxSize = 100
  const ratio = Math.min(maxSize / img.naturalWidth, maxSize / img.naturalHeight)
  canvas.width = img.naturalWidth * ratio
  canvas.height = img.naturalHeight * ratio
  
  // 绘制图片到canvas
  ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
  
  try {
    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
    const data = imageData.data
    
    const colorCounts: { [key: string]: number } = {}
    let totalPixels = 0
    let transparentPixels = 0
    let totalR = 0, totalG = 0, totalB = 0
    
    // 分析每个像素
    for (let i = 0; i < data.length; i += 4) {
      const r = data[i]
      const g = data[i + 1]
      const b = data[i + 2]
      const a = data[i + 3]
      
      // 检查透明度
      if (a < 128) {
        transparentPixels++
      } else {
        // 统计颜色
        const colorKey = `${Math.floor(r / 32)},${Math.floor(g / 32)},${Math.floor(b / 32)}`
        colorCounts[colorKey] = (colorCounts[colorKey] || 0) + 1
        
        totalR += r
        totalG += g
        totalB += b
        totalPixels++
      }
    }
    
    const hasTransparency = transparentPixels > (data.length / 4) * 0.1 // 超过10%透明
    
    // 计算平均颜色
    const avgR = Math.round(totalR / totalPixels) || 0
    const avgG = Math.round(totalG / totalPixels) || 0
    const avgB = Math.round(totalB / totalPixels) || 0
    const avgBrightness = (avgR * 0.299 + avgG * 0.587 + avgB * 0.114) / 255
    
    // 找到主导颜色
    let dominantColorKey = Object.keys(colorCounts).reduce((a, b) => 
      colorCounts[a] > colorCounts[b] ? a : b, Object.keys(colorCounts)[0] || '0,0,0'
    )
    
    const [dR, dG, dB] = dominantColorKey.split(',').map(v => parseInt(v) * 32)
    const dominantBrightness = (dR * 0.299 + dG * 0.587 + dB * 0.114) / 255
    
    const dominantColor: ColorInfo = {
      r: dR,
      g: dG,
      b: dB,
      brightness: dominantBrightness,
      isLight: dominantBrightness > 0.5
    }
    
    const averageColor: ColorInfo = {
      r: avgR,
      g: avgG,
      b: avgB,
      brightness: avgBrightness,
      isLight: avgBrightness > 0.5
    }
    
    // 判断是否需要背景
    const contrastThreshold = props.contrastThreshold || 0.3
    const needsBackground = hasTransparency || 
      (dominantColor.brightness < contrastThreshold || dominantColor.brightness > (1 - contrastThreshold))
    
    // 推荐背景颜色
    let recommendedBackground = ''
    if (needsBackground) {
      if (dominantColor.isLight) {
        // 浅色图片用深色背景
        recommendedBackground = 'rgba(0, 0, 0, 0)'
      } else {
        // 深色图片用浅色背景
        recommendedBackground = 'rgba(255, 255, 255,  0.4)'
      }
      
      // 如果平均亮度接近中等，使用半透明背景
      if (Math.abs(averageColor.brightness - 0.5) < 0.2) {
        recommendedBackground = averageColor.isLight 
          ? 'rgba(0, 0, 0, 0.6)' 
          : 'rgba(255, 255, 255, 0.7)'
      }
    }
    
    const analysis: ImageAnalysis = {
      dominantColor,
      averageColor,
      hasTransparency,
      needsBackground,
      recommendedBackground
    }
    
    imageAnalysis.value = analysis
    emit('analyzed', analysis)
    
  } catch (error) {
    console.warn('图片颜色分析失败:', error)
  }
}
</script>

<style scoped>
.smart-image-container {
  display: inline-block;
  transition: all 0.3s ease;
}

.smart-image {
  max-width: 100%;
  transition: all 0.3s ease;
  opacity: 0;
}

.smart-image.loaded {
  opacity: 1;
}

.smart-image.error {
  opacity: 0.5;
  filter: grayscale(100%);
}

/* 预设样式 */
.smart-image-container.preset-light {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  padding: 4px;
}

.smart-image-container.preset-dark {
  background: rgba(0, 0, 0, 0.7);
  border-radius: 8px;
  padding: 4px;
}

.smart-image-container.preset-shadow {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  border-radius: 6px;
}
</style>
